package com.yc.config;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@Configuration
public class Ip2RegionConfig {

    @Bean
    public Searcher ip2regionSearcher() throws IOException {
        try (InputStream inputStream = new ClassPathResource("ip2region.xdb").getInputStream()) {
            if (inputStream == null) {
                throw new IOException("ip2region.xdb not found in classpath");
            }
            Path tempFile = Files.createTempFile("ip2region", ".xdb");
            Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("DEBUG: Loading ip2region.xdb from: " + tempFile.toAbsolutePath());
            // 使用新版本的 Searcher，支持 .xdb
            return Searcher.newWithFileOnly(tempFile.toString());
        }
    }
}
